package com.ktjy.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * MyBatisUtil 用于初始化 SqlSessionFactory 实例和提供 SqlSession 实例的工具类
 *
 * @author LILIBO
 * @since 2025-10-29
 */
public class MyBatisUtil {

    /**
     * SqlSessionFactory 实例
     */
    private static final SqlSessionFactory sqlSessionFactory;

    /*
     * 静态代码块，初始化 SqlSessionFactory 实例
     */
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取 SqlSession 实例
     *
     * @return SqlSession 实例
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }

    /**
     * 获取 SqlSession 实例
     *
     * @return SqlSession 实例
     */
    public static SqlSession getSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }

    /**
     * 关闭 SqlSession 实例
     *
     * @param sqlSession SqlSession 实例
     */
    public static void closeSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

}
